package com.youzikj.wx.comm.qrcode;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.youzikj.wx.comm.util.CommonUtil;

/**
 * 二维码工具类
 * @author Administrator
 *
 */
public class QrcodeUtil {
	
	private static final Logger log = Logger.getLogger(QrcodeUtil.class);
	
	/**
	 * 创建永久带参的二维码
	 * @param accessToken 接口访问凭证
	 * @param sceneId  场景id
	 * @return
	 */
	public static String createPermanentQRCode(String accessToken,int sceneId){
		String ticket = null;
		//拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		//需要提交的数据
		String jsonMSg ="{\"action_name\":\"QR_LIMIT_SCENE\",\"action_info\":{\"scene\":{\"scene_id\": %d}}}";
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "POST", String.format(jsonMSg, sceneId));
		if(null != jsonObject){
			try {
				ticket = jsonObject.getString("ticket");
				log.info("创建永久的带参二维码成功ticket:"+ticket);
			} catch (Exception e) {
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				log.error("创建永久的带参二维码失败 errorCode:"+errorCode+" errmsg{}"+errorMsg);
			}
		}
		return ticket;
		
	}
	
	/**
	 * 通过ticket换取二维码
	 * @param ticket  二维码ticket
	 * @param savePath  保存路径
	 * @return
	 */
	public static String getQRCode(String ticket, String savePath){
		String filePath = null;
		//凭接请求地址
		String requestUrl ="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
		requestUrl.replace("TICKET", urlEncodeUTF8(ticket));
		try {
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			if(!savePath.endsWith("/")){
				savePath += "/";
			}
			//将ticket作为文件名
			filePath = savePath +ticket +".jpg";
			//将危险服务器返回的输入流写入文件
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			FileOutputStream fos = new FileOutputStream(new File(filePath));
			byte[] buf = new byte[8096];
			int size = 0;
			while((size = bis.read(buf)) != -1)
				fos.write(buf, 0, size);
			fos.close();
			bis.close();
			conn.disconnect();
			log.info("根据ticket换取二维码成功，filePath="+filePath);
		} catch (Exception e) {
			filePath = null;
			log.error("根据ticket换取二维码失败：{}"+e);
		}
		return filePath;
	}
	
	public static String urlEncodeUTF8(String source){
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	

}
